package lab03.test06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

/**
 * Created by dell on 2017/12/7.
 */
public class Test06 {

    public static void main(String[] args) {
        String path="D:\\hello.txt";
        RandomAccessFile file = null;


        Map<String,Integer> map = new HashMap<>();
        try {
            try {
                file = new RandomAccessFile(path,"m");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String line = null;
            int count = 0;
            int num = 0;
            try {
                while((line = file.readLine()) != null){
                    //map中查询
                    count++;

                    if(map.get(line) == null){
                        map.put(line,1);
                        num++;
                    }else{
                        map.put(line,map.get(line)+1);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("有" +count+"个单词");
            System.out.println(num+"个不同的单词");

            for(Map.Entry<String,Integer> a: map.entrySet()){
                System.out.println(a.getKey()+","+a.getValue());
            }

            List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(
                    map.entrySet());
            Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
                public int compare(Map.Entry<String, Integer> o1,
                                   Map.Entry<String, Integer> o2) {
                    return ( o1.getValue()-o2.getValue());
                }
            });
            System.out.println("-排序后-");
            for (int i = 0; i < infoIds.size(); i++) {
                Map.Entry<String, Integer> ent = infoIds.get(i);
                System.out.println(ent.getKey() + "=" + ent.getValue());
            }
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
